package asionreachel.cn.smarthomedemo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import asionreachel.cn.smarthomedemo.R;
import asionreachel.cn.smarthomedemo.base.BaseActivity;
import asionreachel.cn.smarthomedemo.base.BaseDevice;
import asionreachel.cn.smarthomedemo.base.Common;
import asionreachel.cn.smarthomedemo.monitor.JLoginMonitor;
import asionreachel.cn.smarthomedemo.utils.AppUtils;
import familyclient.android.common.JToolFunc;
import familyclient.android.loginmanager.JLoginManagerInterface;
import familyclient.android.loginmanager.JLoginManagerListener;
import familyclient.android.netswitcher.JNetSwitcherInterface;
import familyclient.android.netswitcher.JNetSwitcherListener;

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";
    private static final String FUNCTION = "Login";

    private EditText m_etAccountNum;
    private EditText m_etPassword;

    private JNetSwitcherListener m_listenerNetSwitcher = new JNetSwitcherListener() {
        @Override
        public void ConnectDeviceCb(String a_strDeviceID, String a_strErr) {
            if( !m_bRun )
                return;

            Common.closeDialogLoading();
            if( null != a_strErr && a_strErr.length() > 0 )
            {
                // 直连设备失败
                Common.showToast( Common.MakeMsgByErr( FUNCTION, a_strErr ) );
            }
            else
            {
                // 直连设备成功
                Common.s_bDirectConnect = true;
                Common.s_strFamilyID = "";
                Intent intent = BaseDevice.GetIntent( LoginActivity.this, a_strDeviceID );
                if( intent != null )
                {
                    startActivity(intent);
                }
                else
                {
                    Common.showToast("当前功能尚未完成");
                    JNetSwitcherInterface.GetInstance().DisconnectDevice( a_strDeviceID );
                }
            }
        }
    };

    private JLoginManagerListener m_listenerLoginManager = new JLoginManagerListener() {
        @Override
        public void FamilyLoginCb( String a_strFamilyID, String a_strErr )
        {
            if( !m_bRun )
                return;
            Common.closeDialogLoading();
            if( null == a_strFamilyID || (null != a_strErr && a_strErr.length() > 0) )
            {
                // 登录失败
                Common.showToast( Common.MakeMsgByErr( FUNCTION, a_strErr ) );
            }
            else
            {
                // 登录成功
                Common.showToast(R.string.toast_login_success);
                //保存账号信息
                Common.saveClientAccount(m_etAccountNum.getText().toString() , m_etPassword.getText().toString());
                //跳转功能界面或者功能选择界面
                JLoginMonitor.GetInstance().SetAutoLogin( true );
                Intent intent = new Intent(mActivity , Common.getMainClass());
                startActivity(intent);
                finish();
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        JNetSwitcherInterface.GetInstance().AddListener( m_listenerNetSwitcher );
        JLoginManagerInterface.GetInstance().AddListener( m_listenerLoginManager );
        mActivity = this;
        m_etAccountNum = (EditText)findViewById(R.id.login_ed_account);
        m_etPassword = (EditText)findViewById(R.id.login_ed_pass);
        //m_ivRemenber = (ImageView)findViewById(R.id.login_img_remember);
        Button btLogin = (Button)findViewById(R.id.login_btn_ok);
        TextView tvRegister = (TextView)findViewById(R.id.login_tv_zhuce);
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRegister();
            }
        });

        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLogin();
            }
        });

        //直连模式
        Button btDirect = (Button)findViewById(R.id.login_btn_direct);
        btDirect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDirect();
            }
        });

        TextView btForgotPassWord = (TextView)findViewById(R.id.login_tv_forgot);
        btForgotPassWord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onForgotPassword();
            }
        });
    }

    //初始化账号密码显示
    private void onInit()
    {
        boolean bRemember = Common.getRememberPassword();
        if (bRemember)
        {
            m_etAccountNum.setText(Common.getAccountId());
            m_etPassword.setText(Common.getPassword());
        }
    }

    //点击登录按钮
    private void onLogin()
    {
        Log.d(TAG , "onLogin");
        String strAccount = m_etAccountNum.getText().toString();

        String strFamilyID = "";
        String strPhone = "";
        String strEmail = "";
        if (Common.checkEmail(strAccount))
            strEmail = strAccount;
        else if (Common.checkPhoneNumber(strAccount))
            strPhone = strAccount;
        else if( strAccount.length() > 0 )
            strFamilyID = strAccount;
        else
        {
            Log.e(TAG , "请输入正确ID号码");
            Common.showToast(R.string.toast_correct_account);
            return;
        }
        String strPassWord = m_etPassword.getText().toString();
        if( strPassWord.isEmpty() )
        {
            Log.e(TAG , "密码为空，请输入密码");
            Common.showToast(R.string.toast_null_password);
            return;
        }
        JLoginManagerInterface.GetInstance().FamilyLogin( strFamilyID, strPhone, strEmail, strPassWord );
        Common.showDialogLoading(mActivity , "正在登录");
    }

    //点击注册按钮
    private void onRegister()
    {
        Log.d(TAG , "onRegister");
        Intent intent = new Intent(mActivity,RegisterActivity.class);
        startActivity(intent);
    }

    //点击忘记密码
    private void onForgotPassword()
    {
        Log.d(TAG , "onForgotPassword");
        Common.showToast("暂不开通");
//        Intent intent = new Intent(mActivity,ForgotPasswordActivity.class);
//        startActivity(intent);
    }

    //直连模式
    private void onDirect()
    {
        String strDeviceSSID = AppUtils.getWifiName();
        String strDeviceID = JToolFunc.DeviceSSIDToDeviceID( strDeviceSSID );
        String strDeviceType = JToolFunc.DeviceIDToDeviceType( strDeviceID );
        String strDeviceIP = JToolFunc.DeviceTypeToDeviceApIP( strDeviceType );

        if( null == strDeviceID || 0 == strDeviceID.length() || null == strDeviceIP || 0 == strDeviceIP.length()  ) {
            Common.showToast( "直连失败，请检查设备WIFI连接情况" );
            return;
        }

        JNetSwitcherInterface.GetInstance().ConnectDevice( strDeviceID, strDeviceIP );
        Common.showDialogLoading(mActivity , "正在直连");
    }

    @Override
    protected void onDestroy()
    {
        JLoginManagerInterface.GetInstance().DelListener( m_listenerLoginManager );
        JNetSwitcherInterface.GetInstance().DelListener( m_listenerNetSwitcher );
        super.onDestroy();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if( JLoginMonitor.GetInstance().GetLastCheckLogined() )
        {
            JLoginMonitor.GetInstance().SetAutoLogin( true );
            Intent intent = new Intent(mActivity , Common.getMainClass());
            startActivity(intent);
            finish();
        }
        else
        {
            JLoginMonitor.GetInstance().SetAutoLogin( false );
            onInit();
        }
    }

    @Override
    protected void onPause()
    {
        super.onPause();
    }
}
